package cn.ava.ymcc.mq.consumer;

import cn.ava.ymcc.constants.CommonConstants;
import cn.ava.ymcc.domain.MediaFile;
import cn.ava.ymcc.result.JSONResult;
import cn.ava.ymcc.service.IMediaFileService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.sound.sampled.Line;
import java.io.File;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "service-media-consumer",//消费者组
        topic = "topic-media",//topic
        selectorExpression = "tags-media",//tags
        messageModel = MessageModel.CLUSTERING//集群模式，一个消息只会给到一个消费者
        //还有一个广播模式，一个消息可以被多个消费者消费
)
public class ConsumerMediaMessage implements RocketMQListener<MessageExt> {

    @Autowired
    private IMediaFileService mediaFileService;

    @Value("${media.upload-base-dir}")
    private String uploadPath;

    @Override
    public void onMessage(MessageExt messageExt) {

        String message = new String(messageExt.getBody(), StandardCharsets.UTF_8);

        MediaFile mediaFile = JSONObject.parseObject(message, MediaFile.class);

        JSONResult jsonResult = mediaFileService.handleFile2m3u8(mediaFile);

        if (jsonResult.isSuccess()) {
            mediaFile.setFileStatus(CommonConstants.CourseStateConstant.STATE_TWO); // 处理成功
            // 删除服务地本地的文件
            deleteDir(uploadPath + mediaFile.getFilePath());
        } else {
            mediaFile.setFileStatus(CommonConstants.CourseStateConstant.STATE_THREE); // 处理失败
        }
        mediaFileService.updateById(mediaFile);
    }

    /**
     * 删除本地分片文件
     * @param path
     */
    public static void deleteDir(String path) {
        File dir = new File(path);
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            if (children != null) {
                for (String child : children) {
                    deleteDir(path + "/" + child);
                }
            }
        }
        // 目录此时为空，可以删除
        if (dir.delete()) {
            log.info("文件删除成功!");
        }
    }

}
